package com.hn.log.core;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * hanni
 * 2019/2/20 0020
 * 19:30
 */
@Component  //注入到spring容器中的注解
@Aspect
public class LogAspect {


    @Autowired
    private LogProperties logProperties;

    Logger logger = LoggerFactory.getLogger(getClass());

    //基于包的切面
    //    @Pointcut("execution(* com.hn.controller.*.*(..))")
    //基于自定义注解的切面
    @Pointcut("@annotation(com.hn.log.core.OperationLog)")
    public void pc(){}

    @Around("pc()") //环绕通知
    public Object saveLog(ProceedingJoinPoint joinPoint) {

        try {

            Object proceed = joinPoint.proceed();//继续执行被切割的方法，在这里指的是UserController中的hello方法

            String packages = logProperties.getPackages();
            String toPackage = joinPoint.getTarget().getClass().getPackage().getName();

            System.out.println("packages"+packages);
            System.out.println("toPackage"+toPackage);

            boolean b =  isNeedSaveLog(packages,toPackage);

            if (b){
                logger.info("进入了切面");
            }

            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        return null;
    }


    private boolean isNeedSaveLog(String packages, String toPackage) {
        if (packages == null){
            return true;
        }
        String[] split = packages.split(",");
        for (String s : split) {
            if(toPackage.contains(s)){
                return true;
            }
        }
        return false;
    }
}
